package com.fuxi.cloud.dyndb.util;

import freemarker.cache.StringTemplateLoader;
import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * JmreportFreemarkerParseFactory
 *
 * @Author: 扫地僧
 * @CreateTime: 2021-05-03
 */
public class JmreportFreemarkerParseFactory {
    private static final Logger log = LoggerFactory.getLogger(JmreportFreemarkerParseFactory.class);
    private static final String ENCODE = "utf-8";
    private static final Configuration _tplConfig = new Configuration();
    private static final Configuration _sqlConfig = new Configuration();
    private static StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
    private static final Pattern p = Pattern.compile("(?ms)/\\*.*?\\*/|^\\s*//.*?$");

    public JmreportFreemarkerParseFactory() {
    }

    public static boolean isExistTemplate(String tplName) throws Exception {
        try {
            Template var1 = _tplConfig.getTemplate(tplName, "UTF-8");
            return var1 != null;
        } catch (Exception var2) {
            if (var2 instanceof ParseException) {
                log.error(var2.getMessage(), var2.fillInStackTrace());
                throw new Exception(var2);
            } else {
                log.debug("----isExistTemplate----" + var2.toString());
                return false;
            }
        }
    }

    public static String parseTemplateContent(String tplContent, Map<String, Object> paras) {
        try {
            StringWriter var2 = new StringWriter();
            if (stringTemplateLoader.findTemplateSource("sql_" + tplContent.hashCode()) == null) {
                stringTemplateLoader.putTemplate("sql_" + tplContent.hashCode(), tplContent);
            }

            Template var3 = _sqlConfig.getTemplate("sql_" + tplContent.hashCode(), "utf-8");
            var3.process(paras, var2);
            String var4 = getSqlText(var2.toString());
            return var4;
        } catch (Exception var5) {
            log.error(var5.getMessage(), var5.fillInStackTrace());
            log.error("发送一次的模板key:{ " + tplContent + " }");
            throw new RuntimeException("解析SQL模板异常");
        }
    }

    private static String getSqlText(String sql) {
        sql = p.matcher(sql).replaceAll("");
        sql = sql.replaceAll("\\n", " ").replaceAll("\\t", " ").replaceAll("\\s{1,}", " ").trim();
        if (sql.endsWith("where") || sql.endsWith("where ")) {
            sql = sql.substring(0, sql.lastIndexOf("where"));
        }

        int var1;
        for(var1 = 0; (var1 = StringUtils.indexOfIgnoreCase(sql, "where and", var1)) != -1; sql = sql.substring(0, var1 + 5) + sql.substring(var1 + 9, sql.length())) {
            ;
        }

        for(var1 = 0; (var1 = StringUtils.indexOfIgnoreCase(sql, ", where", var1)) != -1; sql = sql.substring(0, var1) + sql.substring(var1 + 1, sql.length())) {
            ;
        }

        if (sql.endsWith(",") || sql.endsWith(", ")) {
            sql = sql.substring(0, sql.lastIndexOf(","));
        }

        return sql;
    }

    static {
        _tplConfig.setClassForTemplateLoading((new JmreportFreemarkerParseFactory()).getClass(), "/");
        _tplConfig.setNumberFormat("0.#####################");
        _sqlConfig.setTemplateLoader(stringTemplateLoader);
        _sqlConfig.setNumberFormat("0.#####################");
        _sqlConfig.setClassicCompatible(true);
    }
}

